package com.jiahao.material.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiahao.material.entity.Menu;
import com.jiahao.material.entity.Result;
import com.jiahao.material.entity.Role;
import com.jiahao.material.entity.RoleMenu;
import com.jiahao.material.mapper.RoleMenuMapper;
import com.jiahao.material.services.IMenuService;
import com.jiahao.material.services.IRoleService;
import com.jiahao.material.utils.ResultUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @RequiresPermissions("addMenu")
    @PostMapping("/add")
    public Result add(@RequestBody Menu menu) throws Exception{
        menu.setStatus("01");
        menuService.save(menu);
        return ResultUtil.success("添加菜单成功!");
    }


    @GetMapping("/byId/{id}")
    public Result getById(@PathVariable String id) throws Exception{
        Menu byId = menuService.getById(id);
        return ResultUtil.success("",byId);
    }

    @GetMapping("/parentMenu")
    public Result getParentMenu(){
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("parentId","00");
        menuQueryWrapper.orderByAsc("sequence");
        List<Menu> list = menuService.list(menuQueryWrapper);
        return ResultUtil.success("",list);
    }

    @GetMapping("/subMenu")
    public Result getSubMenu(){
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.ne("parentId","00");
        menuQueryWrapper.orderByAsc("sequence");
        List<Menu> list = menuService.list(menuQueryWrapper);
        return ResultUtil.success("",list);
    }

    @RequiresPermissions("updateMenu")
    @PutMapping("/update")
    public Result update(@RequestBody Menu menu) throws Exception{
        menuService.updateById(menu);
        return ResultUtil.success("更新菜单成功!");
    }

    @RequiresPermissions("delMenu")
    @DeleteMapping("/del/{id}")
    public Result delById(@PathVariable String id) throws Exception{
        //先删除菜单与角色的关系
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.eq("mid",id);
        roleMenuMapper.delete(roleMenuQueryWrapper);


        menuService.removeById(id);
        return ResultUtil.success("删除菜单成功!");
    }

}
